<!DOCTYPE html>
{% load static %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>后台管理系统 - {{name}}管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <link rel="stylesheet" href="{% static 'admin/style/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'admin/style/list.css' %}"/>
    <script src="{% static 'admin/js/bootstrap.min.js' %}"></script>
    <script src="{% static 'admin/js/jquery.min.js' %}"></script>
</head>
<body style="position: relative">
<!--条件查询表单-->
<div class="row query">
    <div class="col-12">
        {% for f in fields %}
        {% if f.is_query == '1' %}
        <input type="text" class="queryItem" name="{{f.field}}" class="form-control" placeholder="请输入{{f.remark}}"
               autocomplete="off">
        {% endif %}
        {% endfor %}
    </div>
    <div class="col-2">
        <button type="button" class="btn btn-outline-success" onclick="queryMenus()">查询</button>
        <button type="button" class="btn btn-outline-secondary" onclick="resetMenus()">重置</button>
    </div>
    <div class="col-2">
        {% if insertUrl %}
        <button type="button" class="btn btn-outline-success" onclick="openSave('insert')">新增</button>
        {% endif %}
    </div>
</div>
<hr>
<!--表格渲染-->
<div class = "table_div">
    <table class="table table-hover table-striped" style="text-align: center">
        <thead>
        <tr>
            {% for f in fields %}
            {% if f.not_table_show != '1' %}
            <th scope="col" class="field" name="{{f.field}}">{{f.remark}}</th>
            {% endif %}
            {% endfor %}
            <th scope="col">操作</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
<!--新增&修改 表单-->
<div id="saveView">
    <div class="title">
        新增&修改模板
    </div>
    <hr>
    <div class="form">
    </div>
    <div class="btn">
        <button type="button" class="btn btn-outline-success" onclick="save()">提交</button>
        <button type="button" class="btn btn-outline-secondary" onclick="cloneSave()">关闭</button>
    </div>
</div>
</body>
<script>
    queryMenus();

    //查询列表
    function queryMenus(pageNum) {
        $('tbody').empty();
        $('nav').remove();
        let data = {}
        $('.queryItem').each(function () {
            data[this.name] = this.value
        })
        let url = "";
        if(pageNum){
            url = "{{getListUrl}}?page_number="+pageNum
        }else{
            url = "{{getListUrl}}"
        }
        $.getJSON(
            url,
            data,
            function (res) {
                if (res.code == 200) {
                    let datas = res.data.list;
                    for (let i = 0; i < datas.length; i++) {
                        let data = datas[i];
                        let tr = document.createElement('tr');
                        //获取列名
                        $('.field').each(function () {
                            let field = this.getAttribute('name');
                            let td = document.createElement('td');
                            if (new RegExp("^data:image/jpeg;base64.*$").test(data[field]) ||
                                new RegExp("^data:image/jpg;base64.*$").test(data[field]) ||
                                new RegExp("^data:image/png;base64.*$").test(data[field])
                            ) {
                                let img = document.createElement('img')
                                img.src = data[field]
                                td.append(img)
                            } else {
                                td.textContent = data[field]
                            }
                            tr.append(td)
                        })
                        let operation = document.createElement('td');
                        /*修改按钮*/
                        if ('{{updateUrl}}') {
                            let edit = document.createElement('a');
                            edit.text = '修改'
                            edit.href = 'javascript:void(0)'
                            edit.style.display = 'inline-block'
                            edit.addEventListener('click', function () {
                                openSave('update', data['id'])
                            })
                            operation.append(edit)
                        }
                        /*删除按钮*/
                        if ('{{deleteUrl}}') {
                            let del = document.createElement('a');
                            del.text = '删除'
                            del.href = 'javascript:void(0)'
                            del.style.display = 'inline-block'
                            del.addEventListener('click', function () {
                                delObj(data['id'])
                            })
                            operation.append(del)
                        }
                        tr.append(operation)
                        $("tbody").append(tr)
                    }
                    //添加分页组件
                    if (res.data.page_total > 1) {
                        let nav = document.createElement("nav");
                        nav.setAttribute("aria-label", "Page navigation example");
                        let ul = document.createElement("ul");
                        ul.className = "pagination";
                        let li1 = document.createElement("li");
                        li1.className = "page-item";
                        let a1 = document.createElement("a");
                        a1.className = "page-link"
                        a1.href = "javascript:void(0)"
                        a1.addEventListener('click',function (){
                            if((res.data.page_number-1)>0){
                                queryMenus(res.data.page_number-1)
                            }
                        })
                        a1.textContent="上一页"
                        li1.append(a1)
                        ul.append(li1)
                        for (let i = 0; i < res.data.page_total; i++) {
                            let li = document.createElement("li");
                            if((i+1)==res.data.page_number){
                                li.className = "page-item active"
                            }else{
                                li.className = "page-item";
                            }
                            let a = document.createElement("a");
                            a.className = "page-link"
                            a.href = "javascript:void(0)"
                            a.addEventListener('click',function (){
                                queryMenus(i+1)
                            })
                            a.textContent=i+1+""
                            li.append(a)
                            ul.append(li)
                        }
                        let li2 = document.createElement("li");
                        li2.className = "page-item";
                        let a2 = document.createElement("a");
                        a2.className = "page-link"
                        a2.href = "javascript:void(0)"
                        a2.addEventListener('click',function (){
                            if((res.data.page_number+1)<=res.data.page_total){
                                queryMenus(res.data.page_number+1)
                            }
                        })
                        a2.textContent="下一页"
                        li2.append(a2)
                        ul.append(li2)
                        nav.append(ul)
                        $(".table_div").append(nav)
                    }
                } else {
                    alert("Request error: " + res.msg)
                }
            }
        )
    }

    //重置
    function resetMenus() {
        $("input[name='menu_name']").val("")
        queryMenus()
    }

    //打开新增&修改表单
    function openSave(operationType, id) {
        $("#saveView .title").html(operationType == 'insert' ? '新增' + '{{name}}' : '修改' + '{{name}}')
        if (id) {
            //查询单条信息
            $.getJSON(
                '{{getOneUrl}}',
                {id: id},
                function (res) {
                    $('.saveData').each(function () {
                        if (this.type == 'file') {
                            this.nextSibling.setAttribute('src', res[this.name])
                        } else {
                            this.value = res[this.name]
                        }
                    })
                }
            )
        }
        $("#saveView").css('display', 'block')
    }

    //关闭表单
    function cloneSave() {
        $("#saveView").css('display', 'none')
        $('.saveData').each(function () {
            if (this.type == 'file') {
                this.nextSibling.setAttribute('src', '#')
            } else {
                this.value = ""
            }
        })
    }

    //提交表单
    function save() {
        let reqData = {}
        let flag = true
        $('.saveData').each(function () {

            if (this.type == 'file') {
                let img = this.nextSibling;
                if (img.src == '' || img.src == '#') {
                    flag = false
                }
                reqData[this.name] = img.src
            } else {
                if (this.name != 'id' && this.value == '') {
                    flag = false
                }
                reqData[this.name] = this.value
            }
        })
        console.log(reqData)
        if (flag) {
            let reqUrl = reqData.id ? '{{updateUrl}}' : '{{insertUrl}}'
            $.post(
                reqUrl,
                reqData,
                function (res) {
                    if (res.code === 200) {
                        alert('操作成功！')
                        window.location.reload()
                    } else {
                        alert(res.message)
                    }
                }, 'json'
            )
        } else {
            alert("请完整填写表单！")
        }
    }

    //初始化表单组件
    function loadSaveForm() {
        let fields = eval("{{ fields|safe }}")
        for (let i = 0; i < fields.length; i++) {
            let field = fields[i];
            let row = document.createElement('div');
            row.className = 'mb-3'
            if (field['field'] != 'id') {
                let label = document.createElement('label')
                label.className = 'form-label'
                label.textContent = field['remark']
                row.append(label)
            }
            switch (field.type) {
                case 'select':
                    let select = document.createElement('select')
                    select.className = 'form-select saveData'
                    select.name = field['field']
                    let option = document.createElement('option')
                    option.value = '0'
                    option.text = '无'
                    select.append(option)
                    let values_key = field['field'] + '_values'
                    if (`{{ selectValues|safe }}`) {
                        let selectValues = eval(JSON.parse(`{{ selectValues|safe }}`)[values_key])
                        for (let j = 0; j < selectValues.length; j++) {
                            let selectValue = selectValues[j]
                            let option1 = document.createElement('option')
                            option1.value = selectValue.value
                            option1.text = selectValue.label
                            select.append(option1)
                        }
                    }
                    row.append(select)
                    break;
                case 'images':
                    let img = document.createElement('img')
                    img.src = '#'
                    img.alt = '暂未选择文件'
                    img.style = 'width: 100px;height: 100px;'
                    let file = document.createElement('input')
                    file.className = 'form-control saveData'
                    file.type = 'file'
                    file.accept = 'image/*'
                    file.name = field['field']
                    file.addEventListener('change', function () {
                        preUpload(this)
                    })
                    row.append(file)
                    row.append(img)
                    break
                case 'password':
                    let password = document.createElement('input')
                    password.className = 'form-control saveData'
                    password.type = 'password'
                    password.name = field['field']
                    row.append(password)
                    break
                default:
                    let input = document.createElement('input')
                    input.className = 'form-control saveData'
                    input.type = 'text'
                    input.name = field['field']
                    if (field['field'] == 'id') {
                        input.hidden = 'hidden'
                    }
                    row.append(input)
            }
            $('.form').append(row)
        }
    }

    loadSaveForm()

    //图片预上传
    function preUpload(obj) {
        let file = obj.files[0];//上传的文件
        //文件base64string获取
        if (window.FileReader) {
            let reader = new FileReader();
            reader.readAsDataURL(file);
            //监听文件读取结束后事件
            reader.onloadend = function (e) {
                let base64String = e.target.result;
                let img = obj.nextSibling;
                img.setAttribute('src', base64String)
            };
        }
    }

    //删除操作
    function delObj(id) {
        $.getJSON(
            '{{deleteUrl}}',
            {id: id},
            function (res) {
                if (res.code == 200) {
                    alert('操作成功！')
                } else {
                    alert(res.message)
                }
                window.location.reload()
            }
        )
    }
</script>
</html>